package com.nextbusmn.server.JDOWrappers;

import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import com.nextbusmn.server.dataobjects.NextBusData;

public abstract class JDOWrapper {
	private static final PersistenceManagerFactory pmfInstance = JDOHelper
			.getPersistenceManagerFactory("transactions-optional");
	
	public static PersistenceManagerFactory getPersistenceManagerFactory() {
		return pmfInstance;
	}
	
	private NextBusData data;
	
	public NextBusData getData() {
		return data;
	}
	
	public void setData(NextBusData data) {
		this.data = data;
	}
	
	public void insert() {
		if (!dataExists(data)) {
			PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();
			try {
				System.out.println("Persisting " + data);
				pm.makePersistent(data);
			} finally {
				pm.close();
			}
		} else {
			System.err.println("ERROR: Duplicate attempt");
		}
	}
	
	public static List<? extends NextBusData> getAllRows(Class dataType) {
		PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();
		Query query = pm.newQuery(dataType);
		List<NextBusData> results = null;
		
		try {
			results = (List<NextBusData>) query.execute();
		} finally {
			query.closeAll();
		}
		return results;
	}
	
	public static void deleteAllRows(Class dataType) {
		PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();
		Query query = pm.newQuery(dataType);
		query.deletePersistentAll();
	}
	
	public abstract boolean dataExists(NextBusData data);
}